package ATMAgain;

import javax.swing.*;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Properties;

public class CodeServiceImpl implements ICodeService{

    private static Properties pro = new Properties();
    private static CodeData loginCode;
    static {
        try {
            pro.load(new FileReader("HouseWork0906/src/ATMAgain/atm.txt"));
        }catch (Exception e){
            System.out.println("文件不存在");
        }
    }


    @Override
    public boolean login(String inCode, String inPwd) {
        String value = pro.getProperty(inCode);
        if (value == null) {
            return false;
        }
        String[] array = value.split(",");

        if (inPwd.equals(array[0])){

            loginCode = new CodeData();
            loginCode.setCode(inCode);
            loginCode.setPwd(array[0]);
            loginCode.setMoney(Integer.parseInt(array[1]));

            return true;
        }
        return false;
    }

    @Override
    public CodeData getLoginCode() {
        return loginCode;
    }

    @Override
    public void saveMoney(int money) {
        loginCode.setMoney(loginCode.getMoney()+money);
        this.saveFile();
    }

    /**
     * 储存重写文件
     */
    private void saveFile(){
        pro.setProperty(loginCode.getCode(), loginCode.getPwd()+","+loginCode.getMoney());
        try {
            pro.store(new FileWriter("HouseWork0906/src/ATMAgain/atm.txt"),null);
        }catch (Exception e){
            System.out.println("文件不存在");
        }
    }

    @Override
    public boolean getMoney(int money) {
        if (loginCode.getMoney()<money){
            return false;
        }
        loginCode.setMoney(loginCode.getMoney()-money);
        this.saveFile();
        return true;
    }

    @Override
    public String transMoney(String targetCode, int money) {
        String value = pro.getProperty(targetCode);
        String info = "";
        if (value == null){
            info +=  "汇款账号不存在\n";
        }
        if (loginCode.getMoney()<money){
            info += "账户余额不足\n";
        }
        if (!(info.equals(""))){
            return info;
        }

        loginCode.setMoney(loginCode.getMoney()-money);
        String[] array = value.split(",");
        array[1] = Integer.parseInt(array[1])+money+"";
        pro.setProperty(targetCode,array[0]+","+array[1]);

        this.saveFile();
        return null;
    }

    @Override
    public String changePwd(String oldPwd, String newPwd, String rePwd) {
        if (oldPwd.equals(loginCode.getPwd())==false){
            return "旧密码输入有误";
        }
        if (rePwd.equals(newPwd)==false){
            return "确认密码有误";
        }
        return null;
    }
}
